const vscode = require('vscode');
const ConfigReader = require('../../util/configReader');
const i18n = require('i18next');
const hiSmartLiteEx = require('../../hiSmartLiteEx');

class MenuItemProvider {
  constructor(itemId) {
    this.itemId = itemId;
    this.configReader = new ConfigReader();
  }

  getTreeItem(element) {
    return element;
  }

  async getChildren(element) {
    if (!element) {
      let temp = [];
      const menuItemList = this.configReader.getMenuSectionById(this.itemId);
      if (menuItemList.length === 0) {
        return temp;
      }
      for (const itemObj of menuItemList) {
        if (itemObj.command === 'HiSmartLiteFoundation.openLoginWebview') {
          const isLogin = await this.isLoginPlug();
          itemObj.label = isLogin ? `${i18n.t('hismartlite.foundation.loginOut')}` : itemObj.label;
        }
        const treeItem = new vscode.TreeItem(itemObj.label);
        treeItem.command = {
          command: itemObj.command,
          title: itemObj.command,
          arguments: itemObj.args,
        };
        treeItem.iconPath = itemObj.icon;
        temp.push(treeItem);
      }
      return temp;
    }
    return null;
  }

  getGiteeLoginInfo() {
    const context = hiSmartLiteEx.context;
    const str = context.globalState.get('giteeAuthorization', '{}');
    return JSON.parse(str);
  }

  isLoginPlug() {
    const loginInfo = this.getGiteeLoginInfo();
    return !!loginInfo.giteeLogin;
  }

  initMenu() {
    vscode.window.registerTreeDataProvider('hiSmartLite.setting', new MenuItemProvider('hiSmartLite.setting'));
  }
}

module.exports = MenuItemProvider;